package com.AnywheeBt;

import com.AnywheeBt.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;  
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;  
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;  
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.WindowManager;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadsetClientCall;

import com.AnywheeBt.BTService;
import com.AnywheeBt.PbapClient.utils.ActiconUtil;
import com.AnywheeBt.PbapClient.utils.BTConfig;
import com.AnywheeBt.PbapClient.utils.StringUtils;

public class MainActivity extends Activity {
	protected static final String TAG = "BT";
	private Button mBtnNum[] = new Button[12];
	private TextView mBtStatusTxt = null;
	private TextView mBtDevcieTxt = null;
	private TextView mPhoneNumTxt = null;
	private Button mHomeBtn = null;
	private Button mDelBtn = null;
	private Button mContactBtn = null;
	private Button mStateBtn = null;
//	private Button mYikaBtn = null;
	private Button mDailBtn = null;
	private Button mChangeBtn = null;
	private Button mSettingBtn = null;
	private Button mMusicBtn = null;
	private Button mCallrecordBtn = null;
	
	private  boolean bResume=false;
	private BtMainReceiver nBtMainReceiver = null;
	private String btMacStr = null;
	private boolean bAutoAnwser = true;
	private String bt_conn_statu;

	
	BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
	//private SpeakTts mSpeakTts=null;	
	private boolean isMyServiceRunning(Context context,String ServiceName) {
	    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			Log.i(TAG,"RUNING SEVICE:"+service.service.getClassName());
	        if (ServiceName.equals(service.service.getClassName())) {	        	
	        	return true;
	        }
	    }
	    return false;
	}
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.i(TAG,"onCreate");	 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.bt_main); 
        mBtnNum[0] = (Button) this.findViewById(R.id.main_bt_num0);
        mBtnNum[1] = (Button) this.findViewById(R.id.main_bt_num1);
        mBtnNum[2] = (Button) this.findViewById(R.id.main_bt_num2);
        mBtnNum[3] = (Button) this.findViewById(R.id.main_bt_num3);  
        mBtnNum[4] = (Button) this.findViewById(R.id.main_bt_num4);  
        mBtnNum[5] = (Button) this.findViewById(R.id.main_bt_num5);  
        mBtnNum[6] = (Button) this.findViewById(R.id.main_bt_num6);  
        mBtnNum[7] = (Button) this.findViewById(R.id.main_bt_num7);  
        mBtnNum[8] = (Button) this.findViewById(R.id.main_bt_num8);  
        mBtnNum[9] = (Button) this.findViewById(R.id.main_bt_num9);  
        mBtnNum[10] = (Button) this.findViewById(R.id.main_bt_jin);  
        mBtnNum[11] = (Button) this.findViewById(R.id.main_bt_xin);
        //
//        mHomeBtn = (Button) this.findViewById(R.id.main_laucher_home);
        mDelBtn =(Button) this.findViewById(R.id.main_num_del);
        mContactBtn = (Button) this.findViewById(R.id.main_bt_contact); 
//        mYikaBtn = (Button) this.findViewById(R.id.main_bt_yika);
        mStateBtn =(Button) this.findViewById(R.id.main_bt_state);
        mDailBtn = (Button) this.findViewById(R.id.main_bt_dial);
        mChangeBtn =(Button) this.findViewById(R.id.main_bt_change);
        mSettingBtn = (Button) this.findViewById(R.id.main_bt_setting);
        
        mMusicBtn = (Button)this.findViewById(R.id.main_bt_music);
        mCallrecordBtn = (Button)this.findViewById(R.id.main_bt_callrecord);
        //
        mBtStatusTxt = (TextView)findViewById(R.id.main_bt_status);
        mBtDevcieTxt = (TextView)findViewById(R.id.main_bt_device_name);
        mPhoneNumTxt =(TextView) findViewById(R.id.main_bt_phone_num);
        
        bt_conn_statu = BTApp.getAppConext(this).getProperty("bt_conn_statu");
        if(StringUtils.toBool(bt_conn_statu)){
            mBtStatusTxt.setText(R.string.msg_bt_connect);
        }else{
            mBtStatusTxt.setText(R.string.msg_bt_no_connect);
        }
        
		if(mAdapter.isEnabled()){
        	//imgResetBtn.setBackgroundResource(R.drawable.bohao_press);
			mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
		}
        
		//获取蓝牙Mac地址
        if (mAdapter != null) {   
            btMacStr = mAdapter.getAddress();  
        }
        
        //设置蓝牙设备名称
		SzhBAction.SetLocalBtName(btMacStr + "_CAR-KIT");
        ShowBtName(SzhBAction.GetLocalBtName());

		nBtMainReceiver = new BtMainReceiver();  
        IntentFilter intentFilter = new IntentFilter();  
        intentFilter.addAction("com.anywheeBt.BTMAINRECIVER"); 
        intentFilter.addAction(BTConfig.BT_CONNECTED);
        intentFilter.addAction(BTConfig.BT_DISCONNECTED);
        registerReceiver(nBtMainReceiver, intentFilter);
        //
		if( false == isMyServiceRunning(MainActivity.this,"com.AnywheeBt.BTService")) {
			Log.i(TAG,"******Create BTService.class");
	        Intent msgIntent = new Intent(MainActivity.this,BTService.class);
	        startService(msgIntent);	
	    }

		bAutoAnwser = ((BTApp) getApplication()).isMbAutoAnswer();

//		imgCutSoundBtn.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {				
//				if (SzhBAction.GetBtState()== true) {
//					SzhBAction.SetCmdBt( SzhBAction.AT_CMD_CZ, 0);	
//				}
//				else {
//					Toast.makeText(MainActivity.this,getResources().getString(R.string.msg_connect_error),3).show();
//				}
//			}        	
//        });
		
//		imgHangUpBtn.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {
//				//SzhBAction.terminateCall();
//			}        	
//        });
		
		mSettingBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {				
    			Intent mIntent = new Intent(MainActivity.this, BtSettings.class);
                        mIntent.putExtra("bt_conn_statu", bt_conn_statu);
    			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    			startActivity(mIntent);		
			}        	
        });
		
//		BtoMusics.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {				
//    			Intent mIntent = new Intent(MainActivity.this, BtMusic.class);
//    			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
//    			startActivity(mIntent);	
//			}        	
//        });
		
//        imgResetBtn.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {				
//				 OpenCloseBt();
//			}        	
//        });
        
        mDelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if( strNum.length()>0 ) {
					strNum=strNum.substring(0, strNum.length()-1);
					mPhoneNumTxt.setText(strNum);
				}
				Intent intent = new Intent("com.glsx.bootup.receive.autonavi");
				intent.putExtra("autonaviType", 1); // autonaviType为1：表示直接发起导航请求，
				// autonaviType为2：只进入导航主页面（不发起请求）; 
				sendBroadcast(intent);
				Log.e(TAG, "=====Yanglin======1");
			}	 	
	 	});
	 	
        mDelBtn.setOnLongClickListener( new OnLongClickListener(){
			@Override
			public boolean onLongClick (View arg0){
				if( strNum.length()>0 ) {
					strNum="";
					mPhoneNumTxt.setText(strNum);
				}
				return true;
			}						
		});	
	 	
        mContactBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {	
    			Intent mIntent = new Intent(MainActivity.this, PbList.class);
    			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    			startActivity(mIntent);   
    			Intent intent = new Intent("com.glsx.bootup.receive.autonavi");
    			intent.putExtra("autonaviType", 2); // autonaviType为1：表示直接发起导航请求，
    			// autonaviType为2：只进入导航主页面（不发起请求）; 
    			sendBroadcast(intent);
    			Log.e(TAG, "=====Yanglin======2"); 			
			}

	 	});
	 	
        mStateBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*
    			Intent mIntent = new Intent(MainActivity.this, BtCallList.class);
    			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    			startActivity(mIntent);
    			*/
				if (mAdapter.isEnabled()) {
					Log.d("zcl","bt state true = " + SzhBAction.GetBtState());
					mAdapter.disable();
				} else {
					mAdapter.enable();
					mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
				}
			}	 	
	 	});
	 	
        mDailBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (SzhBAction.GetBtState()== true) {
					if (strNum != "") {
						SzhBAction.CallPhone(strNum);
					}else {
						Toast.makeText(MainActivity.this,getResources().getString(R.string.msg_connects_error),3).show();	
					}
				}else {
					Toast.makeText(MainActivity.this,getResources().getString(R.string.msg_connect_error),3).show();
				}
			}
	 	});
	 	
//	 	mHomeBtn.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(Intent.ACTION_MAIN);
//				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				intent.addCategory(Intent.CATEGORY_HOME);
//				startActivity(intent);
//			} 
//	 	});
//	 	
	 	mChangeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addCategory(Intent.CATEGORY_HOME);
				startActivity(intent);
				*/
				if(!PbCallList.isDelete){
					PbCallList.isSync = 1;
				}else{
					PbCallList.isSync = 2;
				}

				Intent mIntent = new Intent(MainActivity.this, PbList.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(mIntent);

			} 
	 	});
	 	
//	 	//翼卡
//	 	mYikaBtn.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
////				Intent intent = new Intent(Intent.ACTION_MAIN);
////				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////				intent.addCategory(Intent.CATEGORY_HOME);
////				startActivity(intent);
//			} 
//	 	});
	 	
	 	mMusicBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, BtMusic.class);
				startActivity(intent);
			} 
	 	});
	 	mCallrecordBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, BtCallList.class);
				startActivity(intent);
			} 
	 	});
	 	
//	 	imgCannelBtn.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {														
//				AnywheeBtAction.SetCmdBt( AnywheeBtAction.AT_CMD_CG, 0);				
//			}	 	
//	 	});	 	
	 	
	 	mBtnNum[0].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(0);				
			}	 	
	 	});	 
	 	mBtnNum[0].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(0);				
			}	 	
	 	});	 
	 	mBtnNum[1].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(1);				
			}	 	
	 	});	 
	 	mBtnNum[2].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(2);				
			}	 	
	 	});	 
	 	mBtnNum[3].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(3);				
			}	 	
	 	});	 
	 	mBtnNum[4].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(4);				
			}	 	
	 	});	 
	 	mBtnNum[5].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(5);				
			}	 	
	 	});	 
	 	mBtnNum[6].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(6);				
			}	 	
	 	});	 
	 	mBtnNum[7].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(7);				
			}	 	
	 	});	 
	 	mBtnNum[8].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(8);				
			}	 	
	 	});	 
	 	mBtnNum[9].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(9);				
			}	 	
	 	});	 
	 	mBtnNum[10].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(11);				
			}	 	
	 	});	 
	 	mBtnNum[11].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {					
				InputBtNum(10);	
				
			}	 	
	 	});	
	  
	 	
    }

    private String strNum = "";
	private void InputBtNum(int num) {
		Log.e(TAG, ">>>>>>>>>>>>>>>>InputBtNum<<<<<<<<<<<<<");
    	if( strNum.length()>22 ) 
    		return;
    	if(10 == num )  strNum+="*";
    	else if(11 == num )  strNum+="#";
    	else strNum += ("" + num);
    	mPhoneNumTxt.setText(strNum);
    }    
    
    private void OpenCloseBt() {
		//*SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(MainActivity.this);			
		//*boolean bState=prefs.getBoolean("bt_open", true);
		
		boolean bState = mAdapter.isEnabled();
		
		Log.e(TAG,"OpenCloseBt:"+bState);		
		if( bState ) {
			//*if( false==SzhBAction.GetBtStartState() ) return;
			//*if( isMyServiceRunning(MainActivity.this,"com.AnywheeBt.BTService") ) { 			        	
	        //*	Intent msgIntent = new Intent(MainActivity.this,BTService.class);
	        //*	stopService(msgIntent);			        	
	        //*}
			//*prefs.edit().putBoolean("bt_open",false).commit();

			mAdapter.disable();
			
			ShowBtState(false);
			ShowBtName("");
			
	        //imgResetBtn.setBackgroundResource(R.drawable.bohao_1);
	        Toast.makeText(MainActivity.this,getResources().getString(R.string.msg_bt_close),3).show();
	        
		} else {		
			//*if( SzhBAction.GetBtStartState() ) return;
			//*if( false==isMyServiceRunning(MainActivity.this,"com.AnywheeBt.BTService") ) { 			        	
	        //*	Intent msgIntent = new Intent(MainActivity.this,BTService.class);
	        //*	startService(msgIntent);			        	
	        //*}
			//*prefs.edit().putBoolean("bt_open",true).commit();
			
			mAdapter.enable();
			
	        //imgResetBtn.setBackgroundResource(R.drawable.bohao_press);
	        Toast.makeText(MainActivity.this,getResources().getString(R.string.msg_bt_open),5).show();
			mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
	        
		}					
    }
    
    void ShowBtName(String strName) { 
    	//添加Mac地址
    //	String btName = btMacStr + "_" + strName;
    //	Log.e("ShowBtName", "btName = " + btName);

		mBtDevcieTxt.setText(strName);
		
    }
    void ShowBtState(boolean state) {
    	Log.i(TAG,"ShowBtState"+    state   );
    	mBtStatusTxt.setText( state ? R.string.msg_bt_connect:R.string.msg_bt_no_connect);
//    	if (state==false) {
//			//imgBtCallIcon.setVisibility(View.GONE);
//			mBtDevcieTxt.setVisibility(View.GONE);
//		}else {
//			//imgBtCallIcon.setVisibility(View.VISIBLE);
//			mBtDevcieTxt.setVisibility(View.VISIBLE);
//			
//		}
    }
    
    protected void onResume() { 	
		Log.i(TAG,"onResume");
		bResume = true;
		if( SzhBAction.GetBtStartState() ) {
			//*SzhBAction.SetCmdBt(SzhBAction.AT_CMD_MM,0);
		}
		ShowBtName(SzhBAction.GetLocalBtName());
		ShowBtState(SzhBAction.GetBtState());
		super.onResume();
    }
    
    //
    protected void onPause() {        		
		Log.i(TAG,"onPause");		
		bResume=false;	
		super.onPause();
    }	
    @Override
	protected void onDestroy() {
        Log.i(TAG,"onDestroy");	
        unregisterReceiver(nBtMainReceiver);
//    	LogcatHelper.getInstance(this).stop(); 
        if( false==isMyServiceRunning(MainActivity.this,"com.AnywheeBt.BTService")) {
        	}
        //Intent msgIntent = new Intent(MainActivity.this,BTService.class);
    	//stopService(msgIntent);		
        mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);
    	super.onDestroy();
    }

    //
    public class BtMainReceiver extends BroadcastReceiver{    
		@Override  
    	public void onReceive(Context context, Intent intent) {  
    		String str = intent.getAction();
			Log.i(TAG,"******BtMainReceiver:"+str);	
		 	if( str.equals("com.anywheeBt.BTMAINRECIVER" ) ) {
		 		String strMain = intent.getStringExtra("main_str");
		 		if(strMain.equals("finish") ) {
		 			finish();
		 		} else if( strMain.equals("bt_name") ) {
		 			if( bResume ) ShowBtName(SzhBAction.GetLocalBtName());		 							 			
		 		}else if( strMain.equals("bt_state") ) {
		 		}else if(str.equals(ActiconUtil.ACTION_CHOICE_NAV_APPLICATION)){
		 			String choice = intent.getStringExtra(ActiconUtil.DataUtil.CAR_NAV_CHOICE);
		 			if(choice.equals(ActiconUtil.DataUtil.DD_TIGER)){
		 				((BTApp) getApplication()).setDDH(true);
		 			}else if(choice.equals(ActiconUtil.DataUtil.E_CARD)){
		 				((BTApp) getApplication()).setDDH(false);
		 			}
	    		}
		 	}else if(str.equals(BTConfig.BT_CONNECTED)){
		 		mBtStatusTxt.setText(R.string.msg_bt_connect);
		 		bt_conn_statu = "true";
		 	}else if(str.equals(BTConfig.BT_DISCONNECTED)){
		 		mBtStatusTxt.setText(R.string.msg_bt_no_connect);
		 		bt_conn_statu = "false";
		 	}
		}
	}
  
//    //
//    class EditChangedListener implements TextWatcher {  
//		@Override
//		public void onTextChanged(CharSequence s, int start, int before,int count) {
//		}
//		@Override
//		public void afterTextChanged(Editable s) {					
//			int editStart = edBtName.getSelectionStart();  
//			int editEnd = edBtName.getSelectionEnd();  			
//			if(s.length()<1 ) return; 
//			char ch=s.charAt(editStart-1); 
//			if( (ch>='0' && ch<='9') || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z') ) {
//				if( 1==s.length() ) {
//					char chStart=s.charAt(0);
//					if( chStart>='0' && chStart<='9' ) {
//						Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_bt_input_start_error), 3).show();
//						s.delete(editStart - 1, editEnd); 
//					}	
//				} 
//				if( s.length()>6 ) {
//					Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_bt_input_num_error), 3).show();
//					s.delete(editStart - 1, editEnd); 
//				}				
//			} else {
//				Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_bt_input_error), 3).show();
//				s.delete(editStart - 1, editEnd);
//			}
//			//Log.e(TAG,"af s:"+edBtName.getText() +" editStart:"+editStart+" editEnd:"+editEnd+" count"+(editEnd-editStart));				
//		}
//		@Override
//		public void beforeTextChanged(CharSequence s, int start, int count,int after) {	
//			
//		};  
//    }   
}
